import { TypographyTitle } from '@/components/Typography';
import { AutoComplete, Col, Empty, Input, Popover, Spin, Tree } from 'antd';
import cls from 'classnames';
import { ChangeEvent, useContext, useEffect, useMemo, useState } from 'react';
import { ResourcesContext } from '../hooks';
import { IResourceRangeLeftTree } from '../type';
import { SearchOutlined, ReloadOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import { ResourRangeContext } from '../hooks/useResourRangeContext';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import pageStyles from '@/common/pageLayout.less';
import MyIcon from '@/components/MyIcon';
import { loopArray } from '@/utils';

export const ResourceRangeLeftTree: React.FC<IResourceRangeLeftTree> = ({ treeLoading, reloadTree }) => {
  const { prefixCls } = useContext(ResourcesContext);

  const { searchValue, treeData, reloadTableDataSource, resRangeDispatch, selectKeys, expandedKeys, autoExpandParent } =
    useContext(ResourRangeContext);

  /**
   * 显示新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  /**
   * 隐藏新增编辑按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');

  /**
   * 显示 隐藏 详情方法
   * @param openID  显示图标
   * @param closeID  闭合图标
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (openID: string, closeID: string, showPopo: string, isOpen: boolean) => {
    const eleOpen = document.getElementById(openID);
    const eleClose = document.getElementById(closeID);
    if (eleOpen) {
      eleOpen.style.display = isOpen ? 'none' : 'inline-block';
    }
    if (eleClose) {
      eleClose.style.display = isOpen ? 'inline-block' : 'none';
    }
    setShowPopoverID(showPopo);
  };

  // 搜索下拉菜单
  const autoOption = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if (item?.name?.includes(searchValue)) {
          // const name = item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(searchValue);
          // const searchLength = searchValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = searchValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(treeData);

    return option;
  }, [treeData, searchValue]);

  useEffect(() => {
    if (treeData && treeData?.length > 0) {
      onTreeSelect([treeData[0]?.id]);
    }
  }, [treeData]);

  // 保存选中的 tree
  const onTreeSelect = (value: any) => {
    resRangeDispatch({
      type: 'range-selectKeys',
      payload: value,
    });
    if (value && value?.length > 0) {
      const [id] = value;
      reloadTableDataSource(id);
    } else {
      resRangeDispatch({
        type: 'range-selectKeys',
        payload: selectKeys,
      });
    }
  };

  // 保存展开的树 key
  const onTreeExpand = (e: any) => {
    resRangeDispatch({
      type: 'range-expandedKeys',
      payload: e,
    });
    resRangeDispatch({
      type: 'range-autoExpandParent',
      payload: false,
    });
  };
  // 对树结构数据处理
  const loopTreeData = (data: Record<string, any>[]): Record<string, any>[] => {
    return data?.map((item) => {
      const idName = item?.id + 'ShowBtnResouceLeftSendTreeType';
      const detailEyeShow = item?.id + 'eyeShow' + Math.random();
      const detailEyeHiddren = item?.id + 'eyeHiddren' + Math.random();
      const showpopoverDom = item?.id + 'showpopoverDom';
      const flag = false;

      const content = (
        <div style={{ color: '#000000D9' }}>
          <p>
            资源类型：
            {item?.resourceType == '0'
              ? '系统目录'
              : item?.resourceType == '1'
                ? '业务菜单'
                : item?.resourceType == '2'
                  ? '数据范围'
                  : item?.resourceType == '3'
                    ? '功能操作'
                    : '--'}
          </p>
          <p>
            资源状态：
            {item.isOpen == 0 ? <span style={{ color: 'red' }}>禁用</span> : <span style={{ color: 'green' }}>启用</span>}
          </p>
          <p>
            方法类型：
            {item?.method || '--'}
          </p>
          <p>
            资源地址：
            {item?.url || '--'}
          </p>
        </div>
      );
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(searchValue);
      const searchLength = searchValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = searchValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      // if (item?.children) {
      return {
        ...item,
        title: (
          <Popover
            placement="bottomLeft"
            content={content}
            // trigger={'hover'}
            title={item?.name}
            color={'rgb(222 222 222)'}
            overlayClassName={cls('res-popover')}
            destroyTooltipOnHide={{ keepParent: false }}
            open={showpopoverDom == showPopoverID ? true : false}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                overflow: 'hidden',
              }}
              onMouseEnter={() => {
                onTreeNodeMouseEnter(idName, flag);
              }}
              onMouseLeave={() => {
                onTreeNodeMouseLeave(idName, flag);
                clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
              }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  overflow: 'hidden',
                  width: '90%',
                }}
              >
                <MyIcon type={item?.icon} />
                &nbsp;
                {titleTree}
              </div>
              <div
                id={idName}
                style={{
                  whiteSpace: 'nowrap',
                  display: flag ? 'block' : 'none',
                }}
              >
                <a
                  style={{
                    display: 'inline-block',
                    marginRight: 8,
                  }}
                  id={detailEyeShow}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, showpopoverDom, true);
                  }}
                >
                  <EyeOutlined />
                </a>
                <a
                  id={detailEyeHiddren}
                  style={{
                    display: 'none',
                    marginRight: 8,
                  }}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
                  }}
                >
                  <EyeInvisibleOutlined />
                </a>
              </div>
            </div>
          </Popover>
        ),
        key: item?.id,
        children: item?.children ? loopTreeData(item?.children) : null,
      };
      // }
      // return {
      //   ...item,
      //   title: (
      //     <Popover
      //       placement="bottomLeft"
      //       content={content}
      //       trigger={'hover'}
      //       title={item.name}
      //       color={'rgb(222 222 222)'}
      //       overlayClassName={cls('res-popover')}
      //     >
      //       <div
      //         style={{
      //           display: 'flex',
      //           alignItems: 'center',
      //           justifyContent: 'space-between',
      //         }}
      //         id={item?.id}
      //       >
      //         <div
      //           style={{
      //             display: 'flex',
      //             alignItems: 'center',
      //             overflow: 'hidden',
      //           }}
      //         >
      //           <MyIcon type={item?.icon} />
      //           &nbsp;
      //           {titleTree}
      //         </div>
      //       </div>
      //     </Popover>
      //   ),
      //   key: item?.id,
      // };
    });
  };

  // 渲染的树结构数据
  const typeTreeData = useMemo(() => {
    return loopTreeData(treeData);
  }, [treeData, searchValue, selectKeys, showPopoverID]);

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key;
      const targetNode = loopArray(treeData)?.find((i) => i?.id === optionId);
      resRangeDispatch({
        type: 'range-searchValue',
        payload: value,
      });
      resRangeDispatch({
        type: 'range-selectKeys',
        payload: [option?.key],
      });

      resRangeDispatch({
        type: 'range-expandedKeys',
        payload: [targetNode?.pID],
      });
      resRangeDispatch({
        type: 'range-autoExpandParent',
        payload: true,
      });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
        reloadTableDataSource(res);
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'start',
      });
    }
  };

  // 左侧树刷新
  const onReloadTree = () => {
    const promise = new Promise((resolve, reject) => {
      resRangeDispatch({
        type: 'remove-all-state', // 清空state
      });
      resolve(true);
    });
    promise.then((res) => {
      if (res) {
        reloadTree();
      }
    });
  };

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    resRangeDispatch({
      type: 'range-searchValue',
      payload: e.target.value,
    });
  };

  return (
    <>
      <Col span={6} className={cls(prefixCls + 'bottomCol')}>
        <div className={cls(prefixCls + 'tree-box')}>
          <div className={cls(prefixCls + 'tree-header')}>
            <TypographyTitle
              level={4}
              style={{
                margin: 0,
              }}
            >
              资源菜单
            </TypographyTitle>
          </div>
          <div className={cls(prefixCls + 'tree-body')}>
            <div className={cls(prefixCls + 'tree-body-searchInput')}>
              <AutoComplete
                style={{
                  width: '100%',
                }}
                options={autoOption}
                onSelect={onAutoSelect}
              >
                <Input
                  placeholder={'请按名称搜索'}
                  suffix={<SearchOutlined />}
                  onChange={onInputChange}
                  addonAfter={<ReloadOutlined onClick={onReloadTree} />}
                />
              </AutoComplete>
            </div>
            <div className={cls(prefixCls + 'tree-child')}>
              <Spin
                spinning={treeLoading}
                style={{
                  width: '100%',
                  marginTop: 24,
                }}
              >
                <ScrollBarLayout
                  style={{
                    padding: '0.5rem 1rem',
                  }}
                >
                  {treeData && treeData?.length > 0 ? (
                    <Tree
                      treeData={typeTreeData}
                      blockNode={true}
                      selectedKeys={selectKeys}
                      onSelect={onTreeSelect}
                      expandedKeys={expandedKeys}
                      onExpand={onTreeExpand}
                      autoExpandParent={autoExpandParent}
                    />
                  ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                </ScrollBarLayout>
              </Spin>
            </div>
          </div>
        </div>
      </Col>
    </>
  );
};
